package dao.inventory;

import dao.BaseDaoHibernate;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import model.inventory.ItemPrice;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;


@Repository
public class ItemPriceDao extends BaseDaoHibernate<ItemPrice>{
    
    private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(ItemPriceDao.class);
    
    public boolean saveData(List<ItemPrice> itemPrices) {
        Session session = sessionFactory.openSession();
        boolean saved = false;
        try {
            session.beginTransaction();
            for (ItemPrice price : itemPrices) {
                if (price.getPrice().compareTo(BigDecimal.ZERO) > 0) {
                    session.saveOrUpdate(price); 
                }
            }
            
            session.getTransaction().commit();
            saved=true;
        } catch (RuntimeException e) {
            session.getTransaction().rollback(); 
            saved=false;
            log.error("gagal", e);
            java.util.logging.Logger.getLogger(ItemPriceDao.class.getName()).log(java.util.logging.Level.SEVERE, null, e);
        } finally {
            if (session != null) { session.close();}
            return saved;
        }
    }
    
    public List<Date> getDates(int itemId) {
        return sessionFactory.getCurrentSession().createQuery(
                "select distinct id.startDate from ItemPrice where id.itemId = "+itemId+
                " order by id.startDate desc").list();
    }
}
